package com.rent.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rent.common.interceptor.UserContext;
import com.rent.message.mapper.ConversationMapper;
import com.rent.message.pojo.entity.ChatMessage;
import com.rent.message.pojo.entity.Conversation;
import com.rent.message.service.ConversationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements ConversationService {


    @Autowired
    private ConversationMapper conversationMapper;

    @Override
    public void setUnreadCount(Long getUserId,Long postUserId) {
        // 作为 user1 的对话
        LambdaUpdateWrapper<Conversation> wrapper1 = Wrappers.lambdaUpdate(Conversation.class);
        wrapper1.eq(Conversation::getUser1Id, getUserId)
                .eq(Conversation::getUser2Id, postUserId)
                .setSql("user1_unread_count = user1_unread_count" + 1);
        conversationMapper.update(null, wrapper1);

        // 作为 user2 的对话
        LambdaUpdateWrapper<Conversation> wrapper2 = Wrappers.lambdaUpdate(Conversation.class);
        wrapper2.eq(Conversation::getUser2Id, getUserId)
                .eq(Conversation::getUser1Id, postUserId)
                .setSql("user2_unread_count = user2_unread_count" + 1);
        conversationMapper.update(null, wrapper2);
    }

    @Override
    public void updateUnreadCountBatch(Map<String, Integer> unreadCounts) {
        List<LambdaUpdateWrapper<Conversation>> updateWrappers = new ArrayList<>();

        // 为每个会话构造批量更新操作
        for (Map.Entry<String, Integer> entry : unreadCounts.entrySet()) {
            String[] userIds = entry.getKey().split("_");
            Long getUserId = Long.valueOf(userIds[0]);
            Long postUserId = Long.valueOf(userIds[1]);
            Integer unreadCount = entry.getValue();

            // 更新 user1_unread_count
            LambdaUpdateWrapper<Conversation> wrapper1 = Wrappers.lambdaUpdate(Conversation.class);
            wrapper1.eq(Conversation::getUser1Id, getUserId)
                    .eq(Conversation::getUser2Id, postUserId)
                    .setSql("user1_unread_count = user1_unread_count + " + unreadCount);
            if(this.getOne(wrapper1) != null){
                updateWrappers.add(wrapper1);
            }


            // 更新 user2_unread_count
            LambdaUpdateWrapper<Conversation> wrapper2 = Wrappers.lambdaUpdate(Conversation.class);
            wrapper2.eq(Conversation::getUser2Id, getUserId)
                    .eq(Conversation::getUser1Id, postUserId)
                    .setSql("user2_unread_count = user2_unread_count + " + unreadCount);
            if(this.getOne(wrapper2) != null){
                updateWrappers.add(wrapper2);
            }
        }

        // 执行批量更新
        for (LambdaUpdateWrapper<Conversation> wrapper : updateWrappers) {
            conversationMapper.update(null, wrapper);
        }
    }

    @Override
    public void unreadClear(Long userId) {
        Long myUserId = UserContext.getUserId();
        if(myUserId.equals(userId)){
            return;
        }
//        log.info("开始清除未读消息++++,我的id{}，对方id:{}", myUserId, userId);
        // 第一次更新：user1是对方，user2是自己
        LambdaQueryWrapper<Conversation> wrapper = Wrappers.lambdaQuery(Conversation.class);
        wrapper.eq(Conversation::getUser1Id, myUserId)
                .eq(Conversation::getUser2Id, userId)
                .or()
                .eq(Conversation::getUser2Id, myUserId)
                .eq(Conversation::getUser1Id, userId);
        Conversation conversation = conversationMapper.selectOne(wrapper);
        if(conversation == null){
            conversation = new Conversation();
            conversation.setUser1unreadCount(0);
            conversation.setUser2unreadCount(0);
            conversation.setUser1Id(myUserId);
            conversation.setUser2Id(userId);
            this.save( conversation);
            return;
        }

        LambdaUpdateWrapper<Conversation> wrapper1 = Wrappers.lambdaUpdate(Conversation.class);
        wrapper1.eq(Conversation::getUser1Id, userId)
                .eq(Conversation::getUser2Id, myUserId)
                .set(Conversation::getUser2unreadCount, 0);


        conversationMapper.update(null, wrapper1);

        // 第二次更新：user2是对方，user1是自己
        LambdaUpdateWrapper<Conversation> wrapper2 = Wrappers.lambdaUpdate(Conversation.class);
        wrapper2.eq(Conversation::getUser2Id, userId)
                .eq(Conversation::getUser1Id, myUserId)
                .set(Conversation::getUser1unreadCount, 0);


        conversationMapper.update(null, wrapper2);

    }

    @Override
    public Integer getUnreadCount(Long userId, Long myUserId) {
        LambdaQueryWrapper<Conversation> wrapper = Wrappers.lambdaQuery(Conversation.class);

        wrapper.eq(Conversation::getUser1Id, userId)
                .eq(Conversation::getUser2Id, myUserId)
                .or()
                .eq(Conversation::getUser2Id, userId)
                .eq(Conversation::getUser1Id, myUserId);
        Conversation conversation = conversationMapper.selectOne(wrapper);
        if(conversation == null){
            conversation = new Conversation();
            conversation.setUser1unreadCount(0);
            conversation.setUser2unreadCount(0);
            conversation.setUser1Id(userId);
            conversation.setUser2Id(myUserId);
            this.save( conversation);
            return 0;
        }
        return conversation.getUser1Id().equals(myUserId) ? conversation.getUser1unreadCount() : conversation.getUser2unreadCount();
    }

    @Override
    public void setLastMessage(ChatMessage message) {
        LambdaQueryWrapper<Conversation> wrapper = Wrappers.lambdaQuery(Conversation.class);
        wrapper.eq(Conversation::getUser1Id, message.getPostUserId())
                .eq(Conversation::getUser2Id, message.getGetUserId())
                .or()
                .eq(Conversation::getUser2Id, message.getPostUserId())
                .eq(Conversation::getUser1Id, message.getGetUserId());
                Conversation conversation = conversationMapper.selectOne(wrapper);
                if(conversation != null){
                    conversation.setLastMessage(message.getContent());
                    conversation.setLastMessageId(message.getId());
                    conversation.setLastMessageTime(message.getCreated());
                    conversation.setPicture(message.getPicture());
                    conversationMapper.updateById(conversation);
                }else {
                    conversation = new Conversation();
                    conversation.setUser1Id(message.getPostUserId());
                    conversation.setUser2Id(message.getGetUserId());
                    conversation.setLastMessage(message.getContent());
                    conversation.setLastMessageId(message.getId());
                    conversation.setLastMessageTime(message.getCreated());
                    conversation.setPicture(message.getPicture());
                    conversationMapper.insert(conversation);
                }
    }
}
